package service

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"math/rand/v2"
	"regexp"
	"user-srv/basic/config"
	__ "user-srv/basic/proto/rpc"
	"user-srv/handler/model"
)

type UserServer struct {
	__.UnimplementedUserServer
}

func (s *UserServer) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	phone, err := regexp.MatchString("^1[3-9][0-9]{9}$", in.Phone)
	if err != nil {
		return nil, err
	}
	if !phone {
		return nil, fmt.Errorf("手机格式不正确")
	}
	var user model.User
	err = user.IsUser(config.DB, in.Phone)
	if err == nil {
		return nil, fmt.Errorf("手机号已注册")
	}
	user = model.User{
		Phone:     in.Phone,
		Password:  in.Password,
		NickName:  fmt.Sprintf("游客_%d", rand.IntN(10000)),
		AvatarUrl: uuid.New().String() + ".png",
	}
	err = user.Register(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.RegisterResp{
		UserId: int64(user.ID),
	}, nil
}
func (s *UserServer) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var user model.User
	err := user.IsUser(config.DB, in.Phone)
	if err != nil {
		return nil, fmt.Errorf("手机号未注册")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码不正确")
	}
	return &__.LoginResp{
		UserId: int64(user.ID),
	}, nil
}
func (s *UserServer) GetUserInfo(_ context.Context, in *__.GetUserInfoReq) (*__.GetUserInfoResp, error) {
	var user model.User
	err := user.UserInfoById(config.DB, int(in.UserId))
	if err != nil {
		return nil, err
	}
	return &__.GetUserInfoResp{
		Phone:     user.Phone,
		NickName:  user.NickName,
		AvatarUrl: user.AvatarUrl,
	}, nil
}
